<?php
if(!defined('BASEPATH')) exit('No direct script access allowed');
/* 
	微信JS SDK
*/
require_once __DIR__.'/Wechat.php';

class Wechatjs extends Wechat{
	
	// 应用授权作用域
	// snsapi_base 只能获取用户openid
	// snsapi_userinfo 可获取昵称、性别等信息
	private $scope;
	
	public function __construct($option = array()){
		parent::__construct($option);
		$this->scope = isset($option['scope']) ? $option['scope'] : 'snsapi_userinfo';
	}
	
	public function get_openid(){
		$code = htmlspecialchars($_GET['code']);
		if(empty($code)){
			$this->redirect_oauth();
		}else{
			$oauth = $this->get_oauth_accesstoken();
			if(!$oauth['openid']){
				$errcode = $this->error['errcode'];
				if($errcode == 40163){
					// 重复刷新处理
					$this->redirect_oauth();
				}else{
					exit('授权失败：'. $errcode . $this->error['errmsg']);
				}
			}
			$openid = $oauth['openid'];
			return $openid;
		}
	}
	
	// 获取JS接口的签名
	public function get_jssign($url = ''){
		if(!$this->jsapi_ticket && !$this->get_jsticket()){
			return false;
		}
		$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? 'https://' : 'http://';
		$url = $url ? $url : "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
		$jsapiticket = $this->jsapi_ticket;
		$timestamp = time();
		$noncestr = $this->rand_str();
		$string = "jsapi_ticket=$jsapiticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
		$signature = sha1($string);
		$return = array(
			'appid' => $this->appid,
			'noncestr' => $noncestr,
			'timestamp' => $timestamp,
			'url' => $url,
			'signature' => $signature
		);
		return $return;
	}
	
	private function redirect_oauth(){
		$url = $this->get_oauth_redirect($this->get_current_url(), $this->scope);
		Header("Location: $url");
		exit;
	}
	
}